package com.example.springboot.config.springsecurity;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * 配置类
 *
 * @Author:ChenZhangKun
 * @Date: 2020/10/27 21:51
 */
@EnableWebSecurity
public class MySpringSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 授权规则
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 定制请求的授权规则
        http.authorizeRequests()
                .antMatchers("/welcome").permitAll()
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level3/**").hasRole("VIP");
        // 配置自己的登录页
        http.formLogin().usernameParameter("username")
                .passwordParameter("password")
                // 一旦定制loginpage,loginpage的post请求就是登录
                .loginPage("/userlogin");

        // 开启自动配置的登录功能,如果没有权限，就会来到登录页面
        http.formLogin();
        // /login来到登录页
        //
        // 开启自动配置的注销请求
        http.logout()
                // 注销成功后返回的页面
                .logoutSuccessUrl("/welcome");
        // 访问 /logout并清空sessio 注销成功会返回/logou页面
        // 开启记住我功能
        // 登录成功后，会在浏览器中缓存cookie，下一次登录时会在cookie中寻找
        http.rememberMe();
        // 关闭跨域
        http.csrf().disable();
    }

    /**
     * 认证规则
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("zhangsan")
                .password("123456")
                .roles("VIP1", "VIP2")
                .and()
                .withUser("lisi")
                .password("123456")
                .roles("VIP3", "VIP2");
    }
}
